package demo.Thread;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/10-08-10-18:44
 * @Description：demo.Thread
 */
/*
4.先跑完100米者为胜利者
    提示：
1.可以采用Math.random()取得0~1之间的随机数模拟比赛进程
2.如总距离为100米，在随机数0~0.3之间代表兔子跑
3.每次跑2米，在0.3~1之间代表乌龟跑，每次跑1米
4.先跑完100米者为胜利者
 */
public class Run_game {
    static int total_rabbit = 0;
    static int total_turtle = 0;
    public static void main(String[] args) {

        Run_game view = new Run_game();
        Thread rabbit = new Thread("rabbit"){
            @Override
            public void run() {
                while (total_rabbit < 100){
                    synchronized (view){
                        if(total_turtle >= 100){
                            System.out.println("乌龟赢啦！");
                            break;
                        }else if(Math.random() <= 0.3){
                            total_rabbit = total_rabbit + 2;
                            System.out.println("兔子跑了:" + total_rabbit);
                        }else if(total_turtle < 100){
                            view.notify();
                            try {
                                view.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        view.notify();
                    }
                }
                //System.out.println("兔子跑完啦！");
            }
        };
        Thread turtle = new Thread("turtle"){
            @Override
            public void run() {
                while(total_turtle < 100){
                    synchronized (view){
                        if (total_rabbit >= 100){
                            System.out.println("兔子赢啦！");
                            break;
                        }else if(Math.random() > 0.3){
                            total_turtle = total_turtle + 1;
                            System.out.println("乌龟跑了： " + total_turtle);
                        }else if (total_rabbit < 100){
                            view.notify();
                            try {
                                view.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        view.notify();
                    }
                }
                //System.out.println("乌龟跑完啦！");
            }
        };
        rabbit.start();
        turtle.start();

    }
}

